import pygame
import random
from pygame.locals import *

# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Python Typing Wars")

# 颜色定义
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Python 关键词词库
PYTHON_KEYWORDS = [
    "print", "if", "else", "for", "while", "def", "class",
    "import", "return", "try", "except", "with", "as",
    "break", "continue", "pass", "lambda", "raise"
]

# 玩家飞船类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 30))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect(center=(WIDTH//2, HEIGHT-50))
        self.speed = 5

    def update(self, keys):
        if keys[K_LEFT] and self.rect.left > 0:
            self.rect.x -= self.speed
        if keys[K_RIGHT] and self.rect.right < WIDTH:
            self.rect.x += self.speed

# 敌人（单词）类
class Enemy(pygame.sprite.Sprite):
    def __init__(self, word):
        super().__init__()
        self.word = word
        self.font = pygame.font.Font(None, 36)
        self.image = self.font.render(word, True, WHITE)
        self.rect = self.image.get_rect(
            center=(random.randint(50, WIDTH-50), 0)
        )
        self.speed = random.randint(1, 3)

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > HEIGHT:
            self.kill()

# 游戏主逻辑
def main():
    clock = pygame.time.Clock()
    player = Player()
    enemies = pygame.sprite.Group()
    all_sprites = pygame.sprite.Group(player)
    
    current_input = ""
    score = 0
    game_active = True

    # 生成敌人的计时器
    SPAWN_ENEMY = pygame.USEREVENT + 1
    pygame.time.set_timer(SPAWN_ENEMY, 1500)

    while game_active:
        screen.fill((0, 0, 0))  # 清空屏幕
        
        for event in pygame.event.get():
            if event.type == QUIT:
                game_active = False
            elif event.type == SPAWN_ENEMY:
                new_enemy = Enemy(random.choice(PYTHON_KEYWORDS))
                enemies.add(new_enemy)
                all_sprites.add(new_enemy)
            elif event.type == KEYDOWN:
                if event.key == K_BACKSPACE:
                    current_input = current_input[:-1]
                elif event.key == K_RETURN:
                    # 检查输入是否匹配敌人
                    for enemy in enemies:
                        if enemy.word == current_input:
                            enemy.kill()
                            score += 100
                    current_input = ""
                else:
                    current_input += event.unicode.lower()

        # 更新对象
        keys = pygame.key.get_pressed()
        player.update(keys)
        enemies.update()

        # 碰撞检测（敌人触底）
        for enemy in enemies:
            if enemy.rect.bottom >= HEIGHT:
                game_active = False

        # 绘制所有对象
        all_sprites.draw(screen)
        
        # 绘制输入框和分数
        input_font = pygame.font.Font(None, 48)
        input_surface = input_font.render(current_input, True, WHITE)
        screen.blit(input_surface, (20, HEIGHT-80))
        
        score_surface = input_font.render(f"Score: {score}", True, WHITE)
        screen.blit(score_surface, (WIDTH-200, 20))

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()

if __name__ == "__main__":
    main()
